﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using CaseReview.Utility;

namespace CaseReview.DBUtility
{
    public  class SqlHelper {
        public static readonly string ConnectionString =
            ConfigurationManager.ConnectionStrings["dbLocalConnectionString"].ConnectionString;

        public static int executeNonQuery(string cmdText, SqlParameter[] cmdParms)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(Config.ConnStr);
            try
            {
                if (conn.State != ConnectionState.Open)
                    conn.Open();

                cmd.CommandText = cmdText;
                cmd.Connection = conn;
                if (cmdParms != null)
                {
                    foreach (SqlParameter parm in cmdParms)
                    {
                        cmd.Parameters.Add(parm);
                    }
                }
                return cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                return 0;
                throw e;
            }
            finally
            {
                if (conn != null && conn.State == ConnectionState.Open) conn.Close();
            }
        }

        public static SqlDataReader executeReader(string cmdText, SqlParameter[] cmdParms)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(Config.ConnStr);
           // SqlConnection conn = new SqlConnection(ConnectionString);
            try
            {
                if (conn.State != ConnectionState.Open)
                    conn.Open();
                cmd.Connection = conn;
                cmd.CommandText = cmdText;
                if (cmdParms != null)
                {
                    foreach (SqlParameter parm in cmdParms)
                    {
                        cmd.Parameters.Add(parm);
                    }
                }
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch (Exception e)
            {
                if (conn != null && conn.State == ConnectionState.Open) conn.Close();
                throw e;
            }
        }
    }
}
